<template>
  <div>
    <van-icon name="clock-o" style="cursor: pointer;" @click="showPopup = true">
      {{ !timeItems.length ? '选择日期' : timeItems[timeIndex].text }}
    </van-icon>
    <van-popup v-model="showPopup" position="bottom" get-container="body" :style="{ height: '80%' }">
      <van-picker title="选择日期" show-toolbar :columns="timeItems" :default-index="timeIndex" @confirm="onConfirm"
                  @cancel="showPopup = false"/>
    </van-popup>
  </div>
</template>

<script>
import {toDateString} from '@/utils'

export default {
  props: {
    period: String,
    url: String
  },
  data() {
    return {
      timeFormat: {
        h: '%Y-%m-%d %H:%M',
        d: '%Y-%m-%d',
        w: '%Y-%m-%d',
        m: '%Y-%m-%d'
      },
      timeIndex: 0,
      timeItems: [],
      showPopup: false
    }
  },
  methods: {
    onConfirm(_, index) {
      this.timeIndex = index
      this.showPopup = false
      this.$emit('confirm', this.timeItems[index].value)
    },
    load() {
      this.$requests.post(this.url, {period: this.period}).then(resp => {
        if (resp.length > 0) {
          this.timeItems = resp.map(timestamp => {
            return {
              text: toDateString(new Date(timestamp * 1000), this.timeFormat[this.period]),
              value: timestamp
            }
          })
          this.onConfirm({}, resp.length - 1)
        }
      })
    }
  },
  mounted() {
    this.load()
  }
}
</script>
